<?php

namespace app\admin\controller;

use app\admin\controller\Base;
use app\admin\controller\Common;
use app\admin\model\Core;
use app\admin\model\Monitor;
use app\admin\model\Monitor_alarm;
use app\admin\model\Monitor_alarm_history;
use app\admin\model\Room_loop;
use app\admin\model\Email;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use think\Paginator;
use think\Session;

class Alarm extends Base
{
    public function __construct()
    {
        parent::__construct();
        $this->monitor = new Monitor();
        $this->core = new Core();
        $this->monitor_alarm = new Monitor_alarm();
        $this->alarm_history = new Monitor_alarm_history();
        $this->room_loop = new Room_loop();
        $this->email = new Email();
    }

    // 报警设置index
    public function alarmSetting()
    {
        if (session('userinfo')) {
            $monitor_info = $this->monitor->paginate(7);
            $this->assign('monitor_info', $monitor_info);
            return $this->fetch();
        } else {
            return $this->error('请登录', url('admin/admin/login'));
        }
    }

    // 通用更新monitor_alarm数据表
    public function alarmInfoUpdate() {
        // 取出测点定义信息
        $this->coretemp = Loader::model('Core');
        $alltime_info = $this->coretemp->select();
        // 根据core_id，从monitor表中取出每个回路的额定电流温度值，
        // 判断报警状态，加入monitor_alarm表中
        foreach($alltime_info as $alltime_info_item) {
            $temp_core_id = $alltime_info_item['core_id'];
            // dump($temp_core_id);die;
            $temp_current = $alltime_info_item['resi_current'];
            // dump($temp_current);die;
            $temp_tempure = $alltime_info_item['cable_temp'];
            // dump($temp_tempure);die;
            $all_monitor = $this->monitor->column('monitor_id');
            // dump($all_monitor);die;
            if(in_array($temp_core_id, $all_monitor)) {
                // dump(in_array($temp_core_id, $all_monitor));die;
                $normal_current  = $this->monitor->where('monitor_id',$temp_core_id)->column('over_current');
                // dump($normal_current);die;
                $normal_tempure  = $this->monitor->where('monitor_id',$temp_core_id)->column('cable_temp');
                // dump($normal_tempure);die;
                // dump($temp_tempure > $normal_tempure[0]);die;
                $res1 = $temp_tempure > $normal_tempure[0];
                // dump($res1);die;
                if($res1) {
                    $res1 = $this->monitor_alarm->where('monitor_id',$temp_core_id)->update(
                    ['alarm_type' => '0']);
                    // dump($res1);die;
                }
                $res2 = $temp_current > $normal_current[0];
                // dump($res2);die;
                if($res2) {
                    $res2 = $this->monitor_alarm->where('monitor_id',$temp_core_id)->update(['alarm_type' => '1']);
                    // dump($res2);die;             
                }
                // dump(($temp_tempure > $normal_tempure[0]) && ($temp_current > $normal_current[0]));die;
                if(($temp_tempure > $normal_tempure[0]) && ($temp_current > $normal_current[0])) {
                    $res3 = $this->monitor_alarm->where('monitor_id',$temp_core_id)->update(['alarm_type' => '2']); 
                    // dump($res3);die;
                }               
            }

        }
    }

    // 编辑测点预警设置相关信息
    public function updateMonitor($monitor_id)
    {
        if (session('userinfo')) {
            if ($this->request->isPost()) {
                $data = $this->request->only(['loop_name', 'over_current', 'cable_temp','smoke','fire','near_infrared'], 'post');
                // $data['update_time'] = $this->dataNow();
                $res = $this->monitor->save($data, ['monitor_id' => $monitor_id]);
                if ($res) {
                    return $this->success('修改测点信息成功！', url('admin/Alarm/alarmSetting'));
                } else {
                    return $this->error('修改测点信息失败！', url('admin/Alarm/updateMonitor', [
                        'monior_id' => $monitor_id]));
                }
            } else {
                $id = $monitor_id;
                $monitor_info = $this->monitor->where('monitor_id', $id)->find();
                $this->assign('monitor_info', $monitor_info);
                return $this->fetch();
            }
        } else {
            return $this->error('请登录', url('admin/admin/login'));
        }
    }

    // 删除指定测点信息
    public function deleteMonitor($monitor_id)
    {
        if (session('userinfo')) {
            $id = $monitor_id;
            $find_info = $this->monitor->where('monitor_id', $id)->find();
            if (!$find_info) {
                return $this->error('非法操作!', url('admin/Alarm/alarmSetting'));
            }
            $res = $this->monitor->destroy($id);
            if ($res) {
                return $this->success('删除当前测点成功！', url('admin/Alarm/alarmSetting'));
            } else {
                return $this->error('删除当前测点失败!', url('admin/Alarm/alarmSetting'));
            }
        } else {
            return $this->error('请登录', url('admin/admin/login'));
        }
    }

    // 报警响应index
    public function alarmAnswer()
    {
        if (session('userinfo')) {
            $alarm_info = $this->monitor_alarm->paginate(7);
            $this->assign('alarm_info', $alarm_info);


            return $this->fetch();
        } else {
            return $this->error('请登录', url('admin/admin/login'));
        }
    }


    //报警响应日志

    /**
     * @return array
     */
    public function alarmLog()
    {
        $log = [];
        $data_all = $this->monitor_alarm->order('start_time desc')->select();
        foreach ($data_all as $data) {
            // 取出报警点回路名称
            $data['loop_name'] = $this->monitor->where('monitor_id',$data['monitor_id'])->column('loop_name');
            if ($data['alarm_type'] == '0') {
                $data['current_alarm'] = false;
                $data['fire'] = false;
                $data['temp_alarm'] = true;
                $data['near'] = false;
            }elseif ($data['alarm_type'] == '1') {
                $data['current_alarm'] = true;
                $data['temp_alarm'] = false;
                $data['fire'] = false;
                $data['near'] = false;

            }elseif ($data['alarm_type'] == '4'){
                $data['current_alarm'] = false;
                $data['temp_alarm'] = false;                
                $data['fire'] = true;  
                $data['near'] = false;

            }elseif($data['alarm_type'] == '5') {
                $data['current_alarm'] = false;
                $data['temp_alarm'] = false;                
                $data['fire'] = false;  
                $data['near'] = true;                
            }
            else{
                $data['current_alarm'] = false;
                $data['temp_alarm'] = false;                 
                $data['near'] = false;
                $data['fire'] = false;                 
            }
            if($data['mobile_phone'] && ($data['alarm_type'] == '3')) {
                $data['alreadysend'] = true;
            }else {
                $data['alreadysend'] = false;
            }
            // if($data['smoke']) {
            //     $data['smoke'] = '异常';
            // }else {
            //     $data['smoke'] = '正常';
            // }
            // if($data['fire']) {
            //     $data['fire'] = '异常';
            // }else {
            //     $data['smoke'] = '正常';
            // }
            $data['during_time'] = $data['dura_time'];
            $temp = ["shart_time" => $data['start_time'],
                "monitor_id" => $data['monitor_id'],
                "loop_name" => $data['loop_name'],
                "current_alarm" => $data['current_alarm'],
                "temp_alarm" => $data['temp_alarm'],
                "fire" => $data['fire'],
                "near" => $data['near'],
                // "smoke" => $data['smoke'],
                // "fire" => $data['fire'],
                // "near_infrared" => $data['near_infrared'],
                "answer" => $data['status'],
                "alreadysend" => $data['alreadysend']];
                // "during_time" => $data['during_time']];
            array_push($log, $temp);
        }
       // dump($log);die;
        return [
            "data" => $log
        ];
    }

    //报警信息

    /**
     * @return array
     */
    public function alarmInfo()
    {
        $info = [];
        $data_all = $this->alarm_history->limit(30)->select();
        foreach ($data_all as $data) {
            if($data['alarm_type'] == '1'){
                $type = "烟雾报警";
            }elseif($data['alarm_type'] == '0') {
                $type = "温度报警";
            }elseif($data['alarm_type'] == '4') {
                $type = '火灾报警';
            }elseif($data['alarm_type'] == '5') {
                $type = '近红外图像报警';
            }
            $end_time_record = $this->monitor_alarm->where('start_time',$data['start_time'])->find();
            $end_time = $end_time_record['confirm_time'];
            $data['during_time'] = $data['dura_time'];
            $data['alarm_info']="测点: ".$data['monitor_id'].$type;
            $temp = ["alarm_info" => $data['alarm_info'],
                "start_time" => $data['start_time'],
                "confirm_time" => $end_time,
                "user_id" => $data['user_id'],
                "during_time" => $data['during_time']];
            array_push($info, $temp);
        }
        return [
            "data" => $info
        ];
    }

    // 邮件发送
    public function email(){
        if ($this->request->isPost()){
            $data['monitor_id'] = input('monitor_id');
            $data['address'] = input('address');
            $data['alarm_type'] = input('alarm_type');
            if($data['monitor_id'] && $data['address']) {
            // dump($data['monitor_id']);die;
            // 根据monitor_id查询归属位置
            $monitor_location = $this->room_loop->where('loop_id',$data['monitor_id'])->find();
            // dump($monitor_location);die;
            if($monitor_location) {
                $room_id = $monitor_location['room_id'];
                $loop_name = $monitor_location['loop_name'];                
            }else {
                return $this->error('测定信息表(电气室-回路)未找到对应信息！');
            }                
                // 实例化PHPMailer类
                $mail = new PHPMailer(true);
                // 服务器设置
                $mail->SMTPDebug = 2; // 开启Debug
                $mail->isSMTP(); // 使用SMTP
                $mail->Host = 'smtp.qq.com'; // 服务器地址
                $mail->SMTPAuth = true; // 开启SMTP验证
                $mail->Username = '1451171391@qq.com'; // SMTP 用户名
                $mail->Password = 'vykmmvaoamgqgcbj'; // SMTP 密码
                $mail->SMTPSecure = 'ssl'; // 开启TLS 可选
                $mail->Port = 465; // 端口
                // 收件人
                $mail->setFrom('1451171391@qq.com'); // 来自
                $mail->addAddress($data['address']); // 添加一个收件人
                //$mail->addAddress('395696661@qq.com'); // 可以只传邮箱地址
                // 附件
                //$mail->addAttachment('1.jpg'); // 添加附件
                //$mail->addAttachment('2.zip'); // 可以设定名字
                // 内容
                $mail->isHTML(true); // 设置邮件格式为HTML
                $mail->CharSet='UTF-8';
                $mail->Subject = '电气火灾消防预警管理平台——报警通知'; //邮件主题
                $mail->Body = "<h3>实时报警点：<h3 style='color:red;'>{$data['monitor_id']} / {$loop_name}</h3></h3><br/><h3>报警位置：<h3 style='color:red;'>[工厂1] [车间1] [工段1] {$room_id}电气室</h3></h3><br/>
                <h3>报警类型：<h3 style='color:red;'>{$data['alarm_type']}超越额定值！</h3></h3><br>
                "; //邮件内容
                $res = $mail->send();
                if($res) {
                    $email_con['sender'] = $mail->Username;
                    $email_con['receiver'] = $data['address'];
                    $email_con['monitor_id'] = $data['monitor_id'];
                    $email_con['loop_name'] = $loop_name;
                    $email_con['content'] = $mail->Body;
                    $email_con['alarm_type'] = $data['alarm_type'];
                    $email_con['time'] = $this->dataNow();
                    $res_temp = $this->email->save($email_con);
                    if(!$res) {
                        return $this->error('邮件数据存储失败！',url('admin/alarm/alarmanswer'));
                    }
                    // return true;
                    return $this->success('邮件已成功发送',url('admin/alarm/alarmanswer'));
                }else {
                    // return false;
                        return $this->error('邮件发送失败！',url('admin/alarm/alarmanswer'));
                }
            }else {
                return $this->error('测点及email地址不能为空！',url('admin/alarm/alarmanswer'));
            }
        }else {
            
            // return $this->error('非法操作！',url('admin/alarm/alarmanswer'));
        }
    }

    // 报警响应处理
    public function cancel_alarm() {
        // 预判断实时监测各项指标是否正常
         $now_alarm_item = $this->monitor_alarm->where('status',0)->find();
         // dump($now_alarm_item);die;
         $now_monitor_id = $now_alarm_item['monitor_id'];
         $now_info = $this->core->where('core_id',$now_monitor_id)->find();
         $normal_tempure = $this->monitor->where('monitor_id',$now_info['core_id'])->column('cable_temp');
         $normal_near_infrared = $this->monitor->where('monitor_id',$now_info['core_id'])->column('near_infrared');
         // dump($normal_near_infrared[0]);die;
         // dump($normal_tempure);die;
         // dump($now_info['cable_temp']);die;
         $res1 = $now_info['cable_temp'] < $normal_tempure[0];
         $near_res = $now_info['near_infrared'] < $normal_near_infrared[0];
         // dump($res1);die;
         $smoke = $now_info['smoke'];
         $fire = $now_info['fire'];
         if($res1 && !$smoke && !$fire && $near_res) {
             $end_time = $this->dataNow();
             $res = $this->monitor_alarm->where('mobile_phone',0)->update(['alarm_type' => '3','status' => '3','mobile_phone' => '1','confirm_time' => $end_time]);
            if($res) {
            return $this->success('警报已成功消除！',url('admin/alarm/alarmanswer'));
            }else {
            return $this->error('操作失败！',url('admin/alarm/alarmanswer'));
            }
         }else {
            return $this->error('请确认各项指标回归正常！',url('admin/alarm/alarmanswer'));
         }

        // if($this->request->isPost()) {

        // }else {
        //     return '123456';
        // }
    }   

}
